package com.hoangkien.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.hoangkien.config.Core;
import com.hoangkien.network.request.GetListProductRequest;
import com.hoangkien.network.response.GetListPromotionResponse;
import com.hoangkien.network.response.Promotion;
import com.hoangkien.util.Utils;
import android.content.Context;
import android.util.Log;

public class JSONProtocol implements IProtocol {
	private Context context;
	String TAG = "JSONProtocol";

	public JSONProtocol(Context context, Core core) {
		this.context = context;
	}
	
	private synchronized String getDataServerPost(String url, String data)
			throws ClientProtocolException, IOException {
		String responseStr = "";
		StringBuilder builder = new StringBuilder();
		HttpClient httpClient = new DefaultHttpClient();

		try {
			HttpPost httpPost = new HttpPost(url);
			StringEntity se = new StringEntity(data, HTTP.UTF_8);
			httpPost.setEntity(se);
			httpPost.setHeader("Content-Type",
					"application/x-www-form-urlencoded");
			httpPost.setHeader(
					"Security-Code",
					"YgO455jStiyB810F5k8zG4DicEwsYakbJBf4x1Rvnxlge+Th0PDgf/peGKUFKIUtLQm590ILDgUr10LTLSwD8A");
			HttpResponse httpRes = httpClient.execute(httpPost);
			if (httpRes.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = httpRes.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content), 8192);
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
				responseStr = builder.toString();
			}

			Log.d("DATASTR", "Res : " + responseStr);

		} catch (ConnectTimeoutException e) {
			Log.e("JSONProtocol 1070", e.getMessage());
			throw new ClientProtocolException();
		} catch (SocketTimeoutException e) {
			Log.e("JSONProtocol 1073", e.getMessage());
			throw new ClientProtocolException();
		} catch (SocketException e) {
			Log.e("JSONProtocol 1076", e.getMessage());
			throw new ClientProtocolException();
		} catch (UnsupportedEncodingException e) {
			Log.e("JSONProtocol 1079", e.getMessage());
			throw new ClientProtocolException();
		} catch (ClientProtocolException e) {
			Log.e("JSONProtocol 1082", e.getMessage());
			throw e;
		}
		return responseStr;

	}
	
	private Promotion parsePromos(JSONObject obj) {
		// TODO Auto-generated method stub
		Promotion promo = new Promotion();
		String value = "";
		value = obj.optString("ID");
		promo.setID(Utils.validateValue(value));
		value = obj.optString("Title");
		promo.setTitle(Utils.validateValue(value));
		value = obj.optString("Name");
		promo.setName(Utils.validateValue(value));
		value = obj.optString("Intro");
		promo.setIntro(Utils.validateValue(value));
		value = obj.optString("Desc");
		promo.setDesc(Utils.validateValue(value));
		value = obj.optString("Image");
		promo.setImage(Utils.validateValue(value));
		value = obj.optString("Duration_from");
		promo.setDurationFrom(Utils.validateValue(value));
		value = obj.optString("Created_date");
		promo.setCreateTime(Utils.validateValue(value));
		value = obj.optString("Duration_to");
		promo.setDurationTo(Utils.validateValue(value));
		return promo;
	}


	@Override
	public GetListPromotionResponse getListPromos(GetListProductRequest request) throws JSONException, ClientProtocolException, IOException {
		GetListPromotionResponse response = new GetListPromotionResponse();
		JSONObject requestObject = new JSONObject();
		requestObject.put("actionType", METHOD_GET_LIST_PROMOS);
		requestObject.put("pageLimit", request.getPageLimit());
		requestObject.put("pageNumber", request.getPageNumber());
		Log.e(TAG + METHOD_GET_LIST_PROMOS,"content=" + requestObject.toString());
		String strResponse = getDataServerPost(URL, "content=" + requestObject.toString());
		Log.e(TAG + METHOD_GET_LIST_PROMOS, strResponse);
		JSONObject responseObject = new JSONObject(strResponse);
		response.setReturnCode(responseObject.getInt("resultCode"));
		response.setCountPage(responseObject.getInt("countPage"));
		if (response.getReturnCode() == IProtocol.STATUS_CODE_OK) {
			JSONArray jArray = responseObject.optJSONArray("data");
			if (jArray == null) {
				return response;
			}
			ArrayList<Promotion> list = new ArrayList<Promotion>();
			for (int i = 0; i < jArray.length(); i++) {
				JSONObject obj = jArray.optJSONObject(i);
				Promotion promo = parsePromos(obj);
				list.add(promo);
			}
			response.setListCourses(list);
		}

		return response;
	}
}
